package controller;

import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import pojo.Customer;
import service.CustomerManager;
import service.factory.CustomerManagerFactory;

@Controller
@RequestMapping("/")
// @RestController
public class CustomerController {

	private CustomerManager manager;

	public CustomerController() {
		super();
		this.manager = CustomerManagerFactory.getInstance();
	}


	
	/// 异步方式添加数据
		@ResponseBody
		@PostMapping("/add_async")
		public Customer addCustomer(@RequestBody Customer c) {
			System.out.println(c);
			Customer res = this.manager.addCustomer(c);
			if(res!=null) {
				return res;
			}else {
				return null;
			}
		}
		
		//异步方式删除
		@ResponseBody
		@PostMapping("/delete_async")
		public Customer deleteCustomer(String cid) {
			System.out.println(cid);
			String val = cid.split("=")[1];
			Customer res = this.manager.deleteCustomer(val);
			System.out.println("得到了已被删的元素： "+ res);
			if(res!=null) {
				return res;
			}else {
				return null;
			}
		}
		
		//异步方式刷新
		@ResponseBody
		@PostMapping("/update_async")
		public Customer updateCustomer(@RequestBody Customer c) {
			System.out.println("要更新的东西: "+ c);
			Customer res = this.manager.updateCustomer(c);
			
			if(res!=null) {
				return res;
			}else {
				return null;
			}
		}
	

	// 同步方式--------------------------------------------------------------------------------

	/// 同步方式添加数据
	@PostMapping("/add")
	public String addCustomer(Customer c, Model model) {
		Customer res = this.manager.addCustomer(c);
		if (res == null) {
			/// 返回一个空数组
			model.addAttribute("msg", "添加Customer失败，已存在此Customer！");
			return "forward:/error";
		} else {
			/// 重定向到获取列表
			return "redirect:/listAll";
		}
	}

	// 同步方式， 跳转jsp作为响应
	@RequestMapping(value = "/listAll")
	public String findAllCustomers(Model model) {
		List<Customer> list = manager.findAllCustomers();
		System.out.println(list.size());
		model.addAttribute("customers", list);
		return "customer_list";
	}
}
